import { ErrorLevel, MODEL_SERVER_URL, ProjectState, API, ApiCode } from "@/mdesign-lib/mdesign-app.umd.js";
import axios, { AxiosResponse } from "axios";
import { ResData } from "../common";
import { AxiosRequestConfig2, HttpConfig, setupAxios } from "../http";

const httpConfig: HttpConfig = {
  // baseURL: 'http://localhost:3000',
  baseURL: MODEL_SERVER_URL,
  commonHeaders: {},
  postHeaders: {},
  getHeaders: {},
  requestInterceptors: [
    function setTip(config: AxiosRequestConfig2) {
      if (config.tipSuccess === undefined) {
        config.tipSuccess = false;
      }
      if (config.tipError === undefined) {
        config.tipError = true;
      }
      return config;
    }
  ],
  responseInterceptors: [
    function tip(response: AxiosResponse) {
      if (response.data instanceof ArrayBuffer) return response;
      const config = response.config as AxiosRequestConfig2;
      if (response.data.code === ApiCode.SUCCESS && config.tipSuccess) {
        app.$notify({
          title: response.data.title,
          message: response.data.message,
          type: "success"
        });
      } else if (response.data.code !== ApiCode.SUCCESS && config.tipError) {
        let projectId = response.config.params?.projectId || response.config.data?.projectId;
        if (!projectId) {
          try {
            projectId = JSON.parse(response.config.data).projectId;
          } catch (e) {}
        }

        console.log(projectId, response.config, "=========");
        let exceptionType = (response.data?.errorLevel || ErrorLevel.ERROR).toLowerCase?.();
        if (exceptionType === "warn") {
          exceptionType = "warning";
        }
        if (projectId) {
          const project = app.projectManager.getProject(projectId);
          if (!project || project?.ui.closeState === ProjectState.OPENED || response.config.url === API.MODEL_SERVICE_PROJECT_CLOSE) {
            // 带项目id的请求，如果项目没有处于已打开状态则不提示错误，处理请求以发起但是项目被被关闭的情况
            if (response.data.code !== ApiCode.NO_TIP_ERROR) {
              app.$notify({
                title: response.data?.title || "",
                message: response.data?.message || "",
                type: exceptionType
              });
            }
          }
        } else {
          if (response.data.code !== ApiCode.NO_TIP_ERROR) {
            app.$notify({
              title: response.data?.title || "",
              message: response.data?.message || "",
              type: exceptionType
            });
          }
        }
      }
      return response;
    },
    function cleanData(response: AxiosResponse) {
      const result = (response.config as AxiosRequestConfig2).rawData ? response : response.data;
      if (response.data instanceof ArrayBuffer) {
        return response;
      } else if (response.data && response.data.code === ApiCode.SUCCESS) {
        return result;
      } else throw result;
    }
  ]
};
export class ModelHttpClient {
  axios = axios.create({
    withCredentials: false // 是否允许带cookie这些
  });

  constructor() {
    setupAxios(httpConfig, this.axios);
  }

  post<T = ResData<any>>(url: string, data: any, config?: AxiosRequestConfig2): Promise<T> {
    return this.axios.post(url, data, config) as unknown as Promise<T>;
  }
  get<T = ResData<any>>(url: string, params: any = {}, config: AxiosRequestConfig2 = {}): Promise<T> {
    return this.axios.get(url, { params, ...config }) as unknown as Promise<T>;
  }
}

export const modelHttp = new ModelHttpClient();
